package com.tuo51.evaluate.service.tag.impl;

import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Question;
import com.tuo51.evaluate.domain.tags.RelObjectTag;
import com.tuo51.evaluate.domain.tags.Tag;
import com.tuo51.evaluate.repositories.tags.RelObjectTagRepository;
import com.tuo51.evaluate.repositories.tags.TagRepository;
import com.tuo51.evaluate.service.tag.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TagServiceImpl implements TagService {
    @Autowired
    TagRepository tagRepository;

    @Autowired
    RelObjectTagRepository relObjectTagRepository;

    @Override
    public Tag createOrGetTag(String tagName, Integer month) {

        Tag ret = tagRepository.findByTitleAndMonth(tagName, month);

        if (ret == null){
            ret = Tag.of(tagName, month);
            tagRepository.save(ret);
        }

        return ret;
    }

    @Override
    public RelObjectTag createRelation(String tagName, Integer month, String objId, Integer objType) {

        Tag tag = createOrGetTag(tagName, month);

        RelObjectTag relObjectTag = relObjectTagRepository.findByTagIdAndObjIdAndObjType(tag.getId(), objId, objType);
        if (relObjectTag == null){
            relObjectTag = RelObjectTag.of(tag.getId(), objId, objType);
            relObjectTagRepository.save(relObjectTag);
        }

        return relObjectTag;
    }

    @Override
    public RelObjectTag createRelationForQuestion(String tagName, Integer month, EvaluateV2Question question){
        return createRelation(tagName, month, question.getId(), TagObjectType.PBQuestion.getCode());
    }

}
